package cn.bon.websocket.utils;

import cn.bon.websocket.pojo.bo.WebsocketUserBO;
import cn.bon.websocket.pojo.dto.MessageDTO;
import cn.bon.websocket.pool.UserPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * @author: dronff
 * @description: 消息推送类，用于帮助推送消息到指定用户群体,主要功能是筛选要推送给哪些用户
 * @CreateTime: 2023/12/14 9:55
 **/
@Component
public class MessagePushUtils {
    @Resource
    UserPool userPool;

    /**
     * 推送给所有登陆的用户
     * @param messageDTO
     */
    public void pushToAll(MessageDTO messageDTO){
        userPool.forEach(
                (s, websocketUserBO) -> {
                    try {
                        websocketUserBO.push(messageDTO);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
        );
    }

    /**
     * 推送给有指定权限的用户
     */
    public void pushByAuthorities(String authority,MessageDTO messageDTO){
        userPool.forEach(
                new BiConsumer<String, WebsocketUserBO>() {
                    @Override
                    public void accept(String s, WebsocketUserBO websocketUserBO) {
                        websocketUserBO.getGrantedAuthorities().forEach(
                                new Consumer<GrantedAuthority>() {
                                    @Override
                                    public void accept(GrantedAuthority grantedAuthority) {
                                        if (grantedAuthority.getAuthority().equals(authority)) {
                                            try {
                                                websocketUserBO.push(messageDTO);
                                            } catch (JsonProcessingException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                        );
                    }
                }
        );
    }

    public void pushToUser(String username,MessageDTO messageDTO) throws JsonProcessingException {
        WebsocketUserBO websocketUserBO = userPool.get(username);
        if (websocketUserBO == null) {
            return;
        }
        websocketUserBO.push(messageDTO);
    }
}
